<p><code>Optional</code> value can hold either a value or not. The value held in the <code>Optional</code> can be accessed using the
<code>get()</code> method, but it will throw a</p>
<p><code>NoSuchElementException</code> if there is no value present. To avoid the exception, calling the <code>isPresent()</code> or <code>!
isEmpty()</code> method should always be done before any call to <code>get()</code>.</p>
<p>Alternatively, note that other methods such as <code>orElse(...)</code>, <code>orElseGet(...)</code> or <code>orElseThrow(...)</code> can be used
to specify what to do with an empty <code>Optional</code>.</p>
<h2>Noncompliant Code Example</h2>
<pre>
Optional&lt;String&gt; value = this.getOptionalValue();

// ...

String stringValue = value.get(); // Noncompliant
</pre>
<pre>
if (methodThatReturnsOptional().isEmpty()) {
  throw new NotFoundException();
}
String value = methodThatReturnsOptional().get(); // Noncompliant: indirect access, we consider that two consecutive calls can return different values.
</pre>
<h2>Compliant Solution</h2>
<pre>
this.getOptionalValue().ifPresent(stringValue -&gt;
  // Do something with stringValue
);
</pre>
<p>or</p>
<pre>
Optional&lt;String&gt; value = this.getOptionalValue();

// ...

if (value.isPresent()) {
  String stringValue = value.get();
}
</pre>
<p>or</p>
<pre>
Optional&lt;String&gt; value = this.getOptionalValue();

// ...

String stringValue = value.orElse("default");
</pre>
<pre>
Optional&lt;String&gt; optional = methodThatReturnsOptional();
if (optional.isEmpty()) {
  throw new NotFoundException();
}
String value = optional.get();
</pre>
<h2>See</h2>
<ul>
  <li> <a href="https://cwe.mitre.org/data/definitions/476.html">MITRE, CWE-476</a> - NULL Pointer Dereference </li>
</ul>

